import axios from 'axios';

// API Configuration
const CONFIG = {
    AK: import.meta.env.VITE_APP_BAIDU_API_AK,
    SK: import.meta.env.VITE_APP_BAIDU_API_SK,
    BASE_URL: import.meta.env.VITE_APP_API_BASE_URL || 'http://localhost:8000', // 使用后端代理
    DEFAULT_PARAMS: {
        temperature: 0.95,
        top_p: 0.8,
        penalty_score: 1,
        enable_system_memory: false,
        disable_search: false,
        enable_citation: false
    }
};

/**
 * 获取百度API访问令牌
 * @returns {Promise<string>} 访问令牌
 */
async function getAccessToken() {
    try {
        const response = await axios({
            method: 'POST',
            url: `${CONFIG.BASE_URL}/api/baidu/token`,  // 通过后端代理
            data: {
                grant_type: 'client_credentials',
                client_id: CONFIG.AK,
                client_secret: CONFIG.SK
            }
        });
        if (response.data && response.data.access_token) {
            return response.data.access_token;
        } else {
            console.error("无效的响应数据",response?.data);
            throw new Error('获取访问令牌失败：无效的响应数据');
        }
    } catch (error) {
        console.error('获取访问令牌失败:', error);
        throw new Error(error.response?.data?.error_description || '获取访问令牌失败');
    }
}

/**
 * ERNIE API服务类
 */
class ErnieApiService {
    constructor() {
        this.accessToken = null;
        this.tokenExpireTime = null;
    }

    /**
     * 确保访问令牌有效
     */
    async ensureAccessToken() {
        if (!this.accessToken || !this.tokenExpireTime || Date.now() >= this.tokenExpireTime) {
            this.accessToken = await getAccessToken();
            // 令牌有效期设为29天，保险起见提前一天刷新
            this.tokenExpireTime = Date.now() + 29 * 24 * 60 * 60 * 1000;
        }else{
            console.error('请求令牌过期');
        }
        return this.accessToken;
    }

    /**
     * 发送聊天请求
     * @param {Array} messages - 消息数组
     * @param {Object} params - 请求参数
     * @returns {Promise<Object>} 聊天响应
     */
    async chat(messages, params = {}) {
        try {
            const accessToken = await this.ensureAccessToken();
            const response = await axios({
                method: 'POST',
                url: `${CONFIG.BASE_URL}/api/baidu/chat`,  // 通过后端代理
                data: {
                    messages,
                    ...CONFIG.DEFAULT_PARAMS,
                    ...params,
                    access_token: accessToken
                }
            });
            return response.data;
        } catch (error) {
            console.error('聊天请求失败:', error);
            throw new Error(error.response?.data?.error_msg || '聊天请求失败');
        }
    }
}

// 导出单例实例
const ernieApi = new ErnieApiService();
export default ernieApi;

// 使用示例:
/*
import ernieApi from './services/baiduErnieApi';

// 在组件中使用
async function handleChat() {
    try {
        const messages = [
            { role: "user", content: "你好" }
        ];
        const response = await ernieApi.chat(messages);
        console.log(response);
    } catch (error) {
        console.error(error);
    }
}
*/